package com.hy.admin.security.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.admin.security.utils.CommonResult;


/**
 * 说明：自定义 授权失败返回信息
 */
@Component("customAccessDeniedHandler")
public class CustomAccessDeniedHandler implements AccessDeniedHandler {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, 
			AccessDeniedException accessDeniedException) throws IOException, ServletException {
		
		CommonResult result = new CommonResult();
        result.setCode(HttpServletResponse.SC_UNAUTHORIZED);
        result.setMsg(accessDeniedException.getMessage());
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("error", HttpServletResponse.SC_BAD_REQUEST);
        map.put("message", accessDeniedException.getMessage());
        map.put("path", request.getServletPath());
        
        result.setData(map);
		response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
		
		ObjectMapper objectMapper=new ObjectMapper();
		String jsonMsg=objectMapper.writeValueAsString(result);
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(jsonMsg);
      	logger.error(jsonMsg);
	}

}
